import os from "os";
import { Application } from "../Application";
import { logger } from "./logger";
import { miscCfg } from "..";
import { SvrInfo } from "./defines";

/**
 * 解析启动参数 格式:key=value
 * @param args 
 * @returns 
 */
export function parseArgs(args: any[]) {
    let argsMap = {} as any;
    for (let arg of args) {
        let idx = arg.indexOf('=');
        if (idx > -1) {
            let key = arg.slice(0, idx);
            let value = arg.slice(idx + 1);
            if (!isNaN(Number(value)) && (value.indexOf('.') < 0)) {
                value = Number(value);
            } else if (value === "true") {
                value = true;
            } else if (value === "false") {
                value = false;
            }
            argsMap[key] = value;
        }
    }

    return argsMap;
};

/**
 * 是否是本地地址
 * @param host 
 * @returns 
 */
export function isLocalHost(host: string) {
    if (host === "127.0.0.1" || host === "localhost" || host === "0.0.0.0") {
        return true;
    }
    let infos = os.networkInterfaces();
    for (let key in infos) {
        for (let info of infos[key]) {
            if (info.address === host) {
                return true;
            }
        }
    }
    return false;
}

/**
 * 添加服务器
 * @param svr 
 */
export function appAddSvr(app: Application, svr: SvrInfo) {
    if (!svr) return logger.error("试图添加一个不存在的服务器", "util", appAddSvr);
    if (app.hasSvr(svr.id)) return;
    app.svrs[svr.type] ||= [];
    app.svrs[svr.type].push(svr);
    app.svrIdMap[svr.id] = svr;
    miscCfg.onAddSvr && miscCfg.onAddSvr(svr);
}

/**
 * 移除服务器
 * @param svr 
 */
export function appRemoveSvr(app: Application, svr: SvrInfo) {
    if (!svr) return logger.error("试图移除一个不存在的服务器", "util", appRemoveSvr);
    if (!app.hasSvr(svr.id)) return;
    let svrs = app.svrs[svr.type];
    for (let i = svrs.length - 1; i >= 0; i--) {
        if (svrs[i].id === svr.id) {
            svrs.splice(i, 1);
            break;
        }
    }
    miscCfg.onRemoveSvr && miscCfg.onRemoveSvr(svr);
}